<template>
  <div class="app-container">
    <!-- 顶部实时概况数据 -->
    <CompanyTimeData
      v-if="statisticsData.hasOwnProperty('joinAndFreezeOnMonthSum')"
      :status="currentKey"
      :statisticsData="statisticsData"
      @refresh="getStatistics"
    />

    <!-- tab栏 start -->
    <tabs :tabs="tabs" :currentKey="currentKey" @tab-click="tabClick">
      <div>
        <el-button type="primary" @click="toAddCompany">新增企业主</el-button>
        <el-button type="primary" @click="toSetting">参数设置</el-button>
        <el-button type="primary" @click="toInvoice">开票记录</el-button>
      </div>
    </tabs>
    <!-- tab栏 end -->

    <!-- 数据表格 start -->
    <el-card class="mt-20" v-loading="loading">
      <div class="pt-10 pb-10">
        <SearchForm
          :form-option="formOption"
          :show-btn="true"
          :btn-list="btnList"
          v-model="formOption.formData"
          label-width="90px"
        />
      </div>

      <PageTable :data="dataSource" :columns="columns" :options="options" />
      <Pagination
        v-show="total > 0"
        :total="total"
        :pageNo.sync="listQuery.pageNo"
        :pageSize.sync="listQuery.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 数据表格 end -->

    <!-- 审核对话框 -->
    <CompanyAuditDiaLog ref="auditDiaLog" v-model="auditDialogShow" @refreshList="doAuditRefresh" />

    <!-- 冻结理由对话框 -->
    <CompanyReasonDiaLog ref="reasonDiaLog" v-model="reasonDialogShow" :id="reasonId" />
  </div>
</template>

<script>
import _ from 'lodash'
import checkPendingColumsMxin from './checkPendingColums'
import isEnterColumsMxin from './isEnterColums'
import CompanyTimeData from './components/CompanyTimeData.vue'
import CompanyAuditDiaLog from './components/CompanyAuditDiaLog.vue'
import CompanyReasonDiaLog from './components/CompanyReasonDiaLog.vue'

export default {
  name: 'companyList',
  components: {
    // 实时概况
    CompanyTimeData,
    // 审核对话框
    CompanyAuditDiaLog,
    // 冻结理由对话框
    CompanyReasonDiaLog
  },
  mixins: [isEnterColumsMxin, checkPendingColumsMxin],
  props: {},
  data() {
    return {
      // 当前选中tabkey 1:待审核;2:已入驻
      currentKey: '1',
      // 表格tab
      tabs: [
        {
          key: '1',
          label: '待审核',
          value: '1',
          num: 456
        },
        {
          key: '2',
          label: '已入驻',
          value: '2',
          num: 456
        }
      ],

      // 表单搜索配置
      formOption: {
        items: [
          {
            type: 'datetimerange',
            label: '申请时间',
            value: 'time',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            type: 'input',
            label: '企业名称',
            value: 'enterpriseName'
          }
        ],
        formData: {}
      },
      // 表单按钮列表
      btnList: [
        {
          type: 'primary',
          label: '搜索',
          onClick: () => {
            this.listQuery.pageNo = 1
            this.getList()
          }
        },
        {
          label: '重置',
          onClick: () => {
            this.formOption.formData = {}
            this.listQuery.pageNo = 1
            this.getList()
          }
        }
      ],

      // 分页配置
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,

      // 表格加载
      loading: false,
      // 表格配置
      options: {
        border: true,
        select: false
      },
      // 统计数据
      statisticsData: {},
      // 表格源数据
      dataSource: [],

      // 冻结门店理由
      freezeCause: '',

      // 是否显示审核弹窗
      auditDialogShow: false,
      // 是否显示冻结理由对话框
      reasonDialogShow: false,
      // 查看冻结理由企业主id
      reasonId: '',
      avatar: require('@/assets/avatar.png')
    }
  },
  computed: {
    // 表格列
    columns() {
      const defaults = [
        {
          label: '原注册信息',
          width: '180px',
          render: (h, { row }) => {
            return (
              <div style={'display: flex'}>
                {row.profilePhoto ? (
                  <img style={'width: 60px;height: 60px;'} src={row.profilePhoto} />
                ) : (
                  <img style={'width: 60px;height: 60px;'} src={this.avatar} />
                )}
                <div class="ml-10 pt-5 pb-5 flex flex-col justify-between align-start">
                  <p>{row.mobile}</p>
                  <p>{row.nickName}</p>
                </div>
              </div>
            )
          }
        },
        { prop: 'enterpriseName', label: '企业名称', width: '80px' },
        {
          prop: 'licenseNo',
          label: '营业执照号'
        }
      ]
      // 根据当前激活的tab返回列表配置
      const result =
        this.currentKey === '1'
          ? defaults.concat(this.checkPendingColums)
          : defaults.concat(this.isEnterColums)
      return result
    }
  },
  watch: {},
  created() {
    this.getStatistics()
    // 获取待审核列表
    this.getList()
  },
  mounted() {},
  methods: {
    /**
     * tab切换
     * @param {Object} tab tabs项
     */
    tabClick({ key }) {
      this.currentKey = key
      const labelKey = {
        checkPending: '申请时间',
        reject: '入驻时间'
      }
      this.formOption.items[0].label = labelKey[key]
      this.listQuery.pageNo = 1
      this.getList()
    },

    // 获取统计数据
    async getStatistics() {
      try {
        const { data } = await this.$http.user.company.getCount()
        this.statisticsData = data
        this.tabs = this.tabs.map(el => {
          if (el.key === '1') {
            return { ...el, num: data.pendReviewSum + data.rejectSum }
          }
          return { ...el, num: data.freezeSum + data.joinedSum }
        })
      } catch (error) {
        console.log('getStatistics', error)
      }
    },

    // 获取数据列表
    async getList() {
      this.loading = true
      try {
        // 参数处理
        const params = {
          ...this.listQuery,
          listType: this.currentKey,
          enterpriseName: this.formOption.formData.enterpriseName || '',
          startTime: this.formOption.formData.time?.[0] ?? '',
          endTime: this.formOption.formData.time?.[1] ?? ''
        }
        // 发送请求
        const res = await this.$http.user.company.getList({ params })
        // console.log(res)
        // 返回数据进行处理赋值
        this.dataSource = res.data.records.map(el => ({
          ...el,
          causeVisible: false,
          licenseImg: JSON.parse(el.licenseImg)[0]
        }))
        this.total = res.data.total
      } catch (error) {
        console.log('getList', error)
      } finally {
        this.loading = false
      }
    },

    // 审核后刷新数据
    doAuditRefresh() {
      this.getStatistics()
      this.getList()
    },

    /**
     * 待审核列表，点击审核/重审
     * @parma {Object} item 列表数据项
     */
    auditInfo({ id, userId }) {
      this.auditDialogShow = true
      this.$refs.auditDiaLog.eptId = id
      this.$refs.auditDiaLog.userId = userId
      this.$refs.auditDiaLog.getCompanyInfo(id)
    },

    /**
     * 查看冻结理由
     * @parma {Object} item 列表数据项
     */
    lookReason({ id }) {
      this.reasonId = id
      this.$refs.reasonDiaLog.getReason(id)
      this.reasonDialogShow = true
    },

    /**
     * 冻结企业主
     * @param {Object} item 企业主列表项
     */
    doFreeze: _.debounce(function ({ id }) {
      if (!this.freezeCause) {
        this.$message.error('请输入冻结理由')
        return
      }
      // 发送请求更改状态
      this.$http.user.company
        .editVerifyStatus({
          etpId: id,
          reason: this.freezeCause,
          verifystatus: 4
        })
        .then(res => {
          if (res.status === 200) {
            this.$message.success('已冻结')
            this.freezeCause = ''
            this.getList()
          } else {
            this.$message.error(res.msg)
          }
        })
    }, 400),

    /**
     * 解冻企业主
     * @param {Object} item 企业主列表项
     */
    doThawing: _.debounce(function ({ id }) {
      // 发送请求更改状态
      this.$http.user.company
        .editVerifyStatus({
          etpId: id,
          verifystatus: 3
        })
        .then(res => {
          if (res.status === 200) {
            this.$message.success('已解冻')
            this.getList()
          } else {
            this.$message.error(res.msg)
          }
        })
    }, 400),

    /**
     * 点击查看关联用户
     * @param {Object} item 企业主列表项
     * @param {String} is 企业主资料展示tab
     */
    toDetailInfo({ id, userId }, is) {
      this.$router.push({ name: 'CompanyInfo', query: { id, userId, is } })
    },

    // 点击新增企业主
    toAddCompany() {
      this.$router.push({ name: 'CompanyAdd' })
    },

    // 点击参数设置
    toSetting() {
      this.$router.push({ name: 'CompanySetting' })
    },

    // 点击跳转开票
    toInvoice() {
      this.$router.push({ name: 'CompanyInvoice' })
    }
  }
}
</script>

<style lang="scss" scoped></style>
